﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
using SosData;

namespace SosForms
{
    public partial class FormLogin : Form
    {

        #region " Constructores "
        /// <Constructor>
        /// Contructor
        /// </summary>
        public FormLogin()
        {
            InitializeComponent();
        }
        #endregion

        #region " Controles "

        /// <Cancelar login>
        /// Cancelar login. Sale de la aplicacion
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void butCancelar_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <Login>
        /// Login
        /// </Login>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void butLogin_Click(object sender, EventArgs e)
        {
            Autorizado();
        }

        private void txtClave_KeyPress(object sender, KeyPressEventArgs e)
        {
        }

        private void txtClave_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Autorizado();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.CambiarClave();
        }

        #endregion

        #region " Metodos "

        /// <Login>
        /// Login. Check credentials.
        /// </Login>
        public bool Autorizado()
        {
            bool autorizado = SosBL.DataBL.Login(this.txtUsuario.Text, SosBL.SosSecurity.CalculateMD5Hash(this.txtClave.Text));

            if (autorizado)
            {
                this.Close();
            }
            else
            {
                MessageBox.Show("Nombre de usuario o clave incorrecto. Por favor, vuelva a intentarlo", "no autorizado", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            return autorizado;
        }

        /// <summary>
        /// Cambiar clave
        /// </summary>
        private void CambiarClave()
        {
            var db = new sosContext();
            Usuario us = (from u in db.Users.Where(u => u.NickName == this.txtUsuario.Text) select u).FirstOrDefault();

            if (us != null)
            {
                FormCambioPassword cambioFrm = new FormCambioPassword(us, true);
                cambioFrm.Show();
            }
            else
            {
                MessageBox.Show("Este usuario no existe", "Usuario", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        #endregion

    }
}
